﻿//----------------------------------------------------------------
// Copyright (C) 2015-2020 PeachSystem Co.,Ltd.
// All rights reserved.
//
// 文件:JSONHelper.cs
// 摘要:JSON工具类
// 说明:
//

//当前版本：1.0.0
//作    者：陶剑扬
//完成日期：2014-11-07
//----------------------------------------------------------------
using System;
using System.Web;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace PeachSystem.XWX.Helpers
{
    public static class JSONHelper
    {
        /// <summary>
        /// 获取Json
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="t">对象</param>
        /// <returns>Json字符串</returns>
        public static string GetJSON<T>(T t)
        {
            if (t == null) return string.Empty;

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            StringBuilder result = new System.Text.StringBuilder();
            serializer.Serialize(t, result);
            return result.ToString();
        }

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="json">Json字符串</param>
        /// <returns></returns>
        public static T GetEntity<T>(string json)
        {
            if (!string.IsNullOrEmpty(json))
            {
                try
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    return serializer.Deserialize<T>(json);
                }
                catch
                {
                    return default(T);
                }
            }
            else
            {
                return default(T);
            }
        }
    }
}
